import {getWebGLContext, initShaders} from '../../../src/lib/cuon-utils';

// 顶点着色器
const VSHADER_SOURCE = `
    attribute vec4 a_Position;
    void main() {
        gl_Position = a_Position;
        gl_PointSize = 10.0;
    }`;
// 片元着色器
const FSHADER_SOURCE = `
    precision mediump float;    // 精度限定 中等
    uniform vec4 u_FragColor;
    void main() {
        gl_FragColor = u_FragColor;
    }`;

function main() {
    const canvas = document.getElementById('webgl');
    const gl = getWebGLContext(canvas);
    if (!gl) {
        console.log('Failed to get the rendering context for WebGL.');
        return;
    }
    if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
        console.log('Failed to intialize shaders.');
        return;
    }
    const a_Position = gl.getAttribLocation(gl.program, 'a_Position');
    if (a_Position < 0) {
        console.log('Failed to get the storage location of a_Position');
        return;
    }
    const u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');
    if (!u_FragColor) {
        console.log('Failed to get the storage location of u_FragColor');
        return;
    }
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);

    canvas.addEventListener('mousedown', evt => {
        click(evt, gl, canvas, a_Position, u_FragColor);
    });
}

const g_points = [];
const g_colors = [];

function click(evt, gl, canvas, a_Position, u_FragColor) {
    let x = evt.clientX;
    let y = evt.clientY;
    let rect = evt.target.getBoundingClientRect();
    x = ((x - rect.left) - canvas.width * 0.5) / (canvas.width * 0.5);
    y = (canvas.height * 0.5 - (y - rect.top)) / (canvas.height * 0.5);

    g_points.push([x, y]);
    if (x >= 0.0 && y >= 0.0) {
        g_colors.push([1.0, 0.0, 0.0, 1.0]);
    } else if (x < 0.0 && y < 0.0) {
        g_colors.push([0.0, 1.0, 0.0, 1.0]);
    } else if (x > 0.0 && y < 0.0) {
        g_colors.push([0.0, 0.0, 1.0, 1.0]);
    } else {
        g_colors.push([1.0, 1.0, 1.0, 1.0]);
    }

    gl.clear(gl.COLOR_BUFFER_BIT);

    const len = g_points.length;
    for (let i = 0; i < len; i++) {
        const xy = g_points[i];
        const rgba = g_colors[i];

        gl.vertexAttrib3f(a_Position, xy[0], xy[1], 0.0);

        gl.uniform4f(u_FragColor, rgba[0], rgba[1], rgba[2], rgba[3]);

        gl.drawArrays(gl.POINTS, 0, 1);

    }
}


main();
